package edu.zut.main.thread;

public class SynchronizedDemo {
    public static void main(String[] args) {
        TicketDemo ticketDemo = new TicketDemo();
        SaleTicketThreadDemo saleTicketThread = new SaleTicketThreadDemo(ticketDemo);
        SaleTicketThreadDemo saleTicketThread2 = new SaleTicketThreadDemo(ticketDemo);
        SaleTicketThreadDemo saleTicketThread3 = new SaleTicketThreadDemo(ticketDemo);
        new Thread(saleTicketThread,"小花").start();
        new Thread(saleTicketThread2,"小李").start();
        new Thread(saleTicketThread3,"小郭").start();

    }
}
class SaleTicketThreadDemo implements Runnable{
    private TicketDemo ticketDemo;

    public SaleTicketThreadDemo(TicketDemo ticketDemo) {
        this.ticketDemo = ticketDemo;
    }

    @Override
    public void run(){
        //售票操作
        while(true){
            if(ticketDemo.getTicketNum()<=0){
                break;
            }
            ticketDemo.saleTickets();
        }

    }
}
class TicketDemo{//余票


    private int ticketNum = 10;

    public synchronized int getTicketNum() {
        return ticketNum;
    }

    public synchronized void saleTickets(){
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"售出了第"+ticketNum-- +"张票");
    }
}
